﻿using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace InnovTech.Util.ComEx
{
    public abstract class LocalServerComClassBase : MarshalByRefObject
    {
        #region methods
        #region Register functions for the program Regasm.exe

        /// <summary>
        /// This function will be called automatically after the program "Regasm.exe [Assembly_name].exe" is executed.
        /// </summary>
        /// <param name="t"></param>
        [EditorBrowsable(EditorBrowsableState.Never)]
        [ComRegisterFunction()]
        public static void Register(Type t)
        {
            try
            {

                DotNetComEx.SwitchComToLocalServer(t);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message); // Log the error
                throw ex; // Re-throw the exception
            }
        }

        /// <summary>
        ///  This function will be called automatically after the program "Regasm.exe /u [Assembly_name].exe" is executed.
        /// </summary>
        /// <param name="t"></param>
        [EditorBrowsable(EditorBrowsableState.Never)]
        [ComUnregisterFunction()]
        public static void Unregister(Type t)
        {
            try
            {
                DotNetComEx.UnregisterComponent(t);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message); // Log the error
                throw ex; // Re-throw the exception
            }
        }

        #endregion Register functions for the program Regasm.exe

        #endregion methods

        #region constructor
        public LocalServerComClassBase()
        {
            ComLocalServer.Instance.Lock();
        }

        ~LocalServerComClassBase()
        {
            OnFinalRelease();
            ComLocalServer.Instance.Unlock();
        }
        #endregion constructor

        public virtual void OnFinalRelease(){}
    }
}
